from users.models import *
from django.core.mail import send_mail
from django.contrib.auth.hashers import make_password
from datetime import  datetime
import hashlib
from cdk.settings import EMAIL_FROM
# 发送验证码
def sendEmail(email,send_type,new_email=""):
    now = datetime.now()
    timeStr = str(now.year)+str(now.hour)+str(now.minute)
    if send_type == 'register':
        code = make_password(email + send_type, None, 'pbkdf2_sha256')[-10:]
    elif send_type == 'getPwdBack':
        code = make_password(email + send_type + timeStr, None, 'pbkdf2_sha256')[-10:]
    elif send_type == 'alterEmail':
        code = hashlib.md5(str(new_email + send_type).encode('utf-8')).hexdigest()[-10:]
        # code = make_password(new_email + send_type,None,'pbkdf2_sha256')
    email_record = EmailVerifyRecord()
    email_record.code  = code
    email_record.email = email
    email_record.send_type = send_type
    email_record.save()
    code = str(code)
    code = code.replace("/","*")
    # 发送邮件
    subject = ''
    message = ''
    if send_type == 'register':#注册
        subject = '完成注册'
        message = '请查看这里'+':http://127.0.0.1:8000/emailActivate/'+code
        print(message,code)
        send_mail(subject,message,EMAIL_FROM,[email_record.email])
    elif send_type == 'getPwdBack':#忘记密码
        subject = '密码找回'
        message = '请查看这里' + ':http://127.0.0.1:8000/reSetPwdByEmailVerify/' + code
        print(message, code)
        send_mail(subject, message, EMAIL_FROM, [email_record.email])
    elif send_type == 'alterEmail':#修改邮箱
        subject = '修改绑定邮箱'
        message = '请查看这里' + ':http://127.0.0.1:8000/alterEmailVerify/' + code +"/" + new_email
        print(message, code)
        send_mail(subject, message, EMAIL_FROM, [email_record.email])